import type {
  DrawerProps
} from './typing';
import {
  getCurrentInstance,
  nextTick, App, ComponentInternalInstance, createVNode, render
} from "vue";
import { HookDrawerProps } from "./typing";
import { myDrawer } from "./drawer";
let _app: App;

export const useDrawer = ()=>{
  let _modalInstance: ComponentInternalInstance;
  const appContext = _app._context || getCurrentInstance()?.appContext;
  const getModalInstance = () => {
    if (_modalInstance) {
      return _modalInstance;
    }
    const container = document.createElement('div');
    const vnode = createVNode(myDrawer);
    vnode.appContext = appContext;
    render(vnode, container);
    _modalInstance = vnode.component!;
    _modalInstance.props.closeFunc = hide
    return _modalInstance;
  };
  const hide = () => {
    const modalInstance = getModalInstance();
    Object.assign<any, HookDrawerProps>(modalInstance?.props, {
      visible: false,
    });
    return true;
  };

  const show = async (props: HookDrawerProps) => {
    const modalInstance = getModalInstance();
    Object.assign<any, HookDrawerProps>(modalInstance?.props, {
      ...props,
      visible: true,
    });
    await nextTick();
  };
  const setDrawerProps = (props)=>{
    const modalInstance = getModalInstance();
    Object.assign<any, DrawerProps>(modalInstance?.props, props);
  }

  return {
    show,hide,
    setDrawerProps
  }

}

export const install = (app: App) => {
  _app = app;
};
